package com.qcby.demo;

import java.util.ArrayList;
import java.util.List;

/**
 * 事务管理类
 */
public class TransactionManager {
    private List<TransactionOperation> operations = new ArrayList<>();

    // 添加一个操作到事务中
    public void addOperation(TransactionOperation operation) {
        operations.add(operation);
    }

    // 提交事务
    public void commit() {
        System.out.println("事务提交成功");
    }

    // 执行所有操作
    public void execute() {
        try {
            for (TransactionOperation operation : operations) {
                operation.execute();
            }
            commit(); // 如果所有操作都成功，则提交事务
        } catch (Exception e) {
            System.out.println("操作出现异常，正在回滚事务...");
            rollback(); // 出现异常则回滚
        }
    }

    // 回滚事务
    public void rollback() {
        for (int i = operations.size() - 1; i >= 0; i--) {
            operations.get(i).rollback();
        }
        System.out.println("事务回滚成功");
    }
}
